import { scrollMixin } from "utils/mixin";
import { debounceEnd } from 'utils/tool';
import BScroll from "better-scroll";
import yzService from "components/ui_components/yz_service";
export default {
  components: {
    yzService
  },
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      swiperOption: {
        direction: "horizontal",
        autoHeight: true,
        autoplay: false,
        pagination: false,
        loop: true,
        initialSlide: 0
      },
      active: 1,
      isBgFlag: false,
      addressOpen: false,
      makeOpen: false,
      subscribeFlag: false,
      addressValue: 0,
      presentTime: "",
      addressList: [],
      cityText: "全部区域",
      cityValue: "", //获取城市编码的
      addressCity: "", //显示站点的
      query: {
        //筛选商品的
        page: 1,
        longitude: "",
        latitude: "",
        city: "",
        travel_around_goods_type: 0,
        is_recommand: 0,
        category: 0,
        title: "",
        cityCode: ""
      },
      subscribeText: "全部分类",
      addIndex: -1,
      subscribeIndex: 0,
      optionIndex: 1,
      now: "",
      container: null,
      indexBanner: [], //轮播图
      activityList: [], //分类
      classifyList: [], //分类
      rankingList: [],
      goodsList: [],
      locationStatus: false, //判断是否有传定位
      isLoadMore: true,
      showCservice: false, //客服开关
      page: 1,
      total_page: 0,
      locationMore: true,
      //客服插件
      serviceShow: false,
      serviceQRcode: "",
      serviceMobile: "",
      cservice: "",
      localCity:'',
      storeScroll:"",
      goodsFlag:false,
      // scrollToTop:0
    };
  },
  computed: {},
  activated() {
    this.now = new Date(this.timestampToTime(new Date().valueOf() / 1000)).valueOf() / 1000;
    this.presentTime = new Date().getTime();
    this.Move();
    if ((this.$route.query.city ?? "") !== "") {
      //获取站点的编码
      this.cityValue = Number(this.$route.query.cityCode);
      this.query.cityCode = Number(this.$route.query.cityCode);
      this.query.city = this.$route.query.city;
      this.addressCity = this.$route.query.city;
      this.localCity = this.$route.query.localCity;
      this.aroundLocation();
    }
    let myLocation = this.$store.state.o2oLocation;//获取缓存定位信息
    this.travelIndexData();
    if(!myLocation.point) this.getGoodsList(true);
    if(myLocation.point) {
      let point = myLocation.point;
      this.query.latitude = point.lat;
      this.query.longitude = point.lng;
      let adcode = myLocation.addressComponent?.adcode;
      let interceptionCity = adcode.toString().slice(0, 4) + "00";
      if (this.addressCity === "") {
        this.addressCity = myLocation.city;
        this.query.city = myLocation.city;
        this.cityValue = interceptionCity;
      }
      this.query.cityCode = interceptionCity;
      this.getGoodsList();
    }
        
      // }
    this.getGood();
    
  },
  mounted() {
    
    this.container = this.$refs.container;
    window.addEventListener('scroll', this.scrollToTop)
  },
  destroyed () {
    window.removeEventListener('scroll', this.scrollToTop)
  },

  filters: {
    kmUnit(value) {
      let val = parseInt(value);
      let v;
      if (typeof val === "number" && !isNaN(val)) {
        if (val >= 1000) {
          v = (val / 1000).toFixed(2) + "km";
        } else {
          v = val + "m";
        }
      } else {
        v = "0m";
      }
      return v;
    }
  },
  methods: {
    loadPrimse() {
      return pro;
    },
    showStore() {
      this.$nextTick(() => {
        if (!this.storeScroll) {
          // this._initScrollCart();
          this._initScrollTime();
          
        } else {
          this.storeScroll.refresh();
        }
        if (!this.classScroll) {
          this._initScrollClass();
        } else {
          this.classScroll.refresh();
        }
      });
    },
    _initScrollTime() {
      if (this.activityList.length > 0) {
        this.storeScroll = new BScroll(this.$refs.handpickList, {
          scrollX: true,
          click: true
        });
      }
    },
    _initScrollClass() {
      if (this.classifyList.length > 0) {
        this.classScroll = new BScroll(this.$refs.classifyRef, {
          scrollX: true,
          click: true
        });
      }
    },
    travelIndexData() {
      let cityCode = '';
      let city = '';
      if(this.localCity) {
        city = this.localCity;
      } else {
        cityCode = this.query.cityCode||'';
      }
      //轮播图和分类信息
      $http.get("plugin.travel-around.frontend.index.index", {city:city,cityCode:cityCode,basic_info:1}, "加载中..").then(response => {
        if (response.result == 1) {
          let res = response.data;
          let basicInfo = response.basic_info
          this.activityList = res.category;
          if (this.activityList.length > 10) {
            //超过十个拆分数组换行显示
            let classify = this.activityList.splice(10, this.activityList.length - 10);
            this.classifyList = classify;
          }
          this.showStore();
          this.$nextTick(() => {
            this.fun.wxShare(
              "",
              { mid: this.fun.getKeyByMid() },
              {
                link: window.location.href,
                title: '周边游-'+basicInfo?.home.mailInfo?.name,
                imgUrl: basicInfo?.home.mailInfo?.logo_url,
                description: '全国周边吃喝玩乐特惠套餐！'
              }
            );
          },50);
          this.rankingList = res.goods;
          this.indexBanner = res.banner;
         
        } else {
          this.$dialog.alert({
            message: response.msg
          });
        }
      });
    },
    showService() {
      this.serviceShow = true;
    },
    searchOn() {
      this.$router.push(this.fun.getUrl("tourAroundTourSearch", {}, { keyWord: this.query.title,city:this.localCity,latitude: this.query.latitude ,longitude:this.query.longitude,cityCode:this.query.cityCode }));
    },
    rankingOn(id) {
      this.$router.push(this.fun.getUrl("tourAroundGoodsDetails", {}, { goodsId: id,latitude: this.query.latitude ,longitude:this.query.longitude}));
    },
    subscribeSticky(event) {
      this.subscribeFlag = event;
    },
    subscribeOn(index) {
      //筛选信息
      if (index === 3) {
        this.makeOpen = true;
        this.addressOpen = false;
        
        if (this.isBgFlag) { //吸顶不吸顶的判断是否显示背景色
          this.subscribeFlag = true;
        } else { 
          this.subscribeFlag = false;
          if (this.addressOpen || this.makeOpen) { //存在打开弹窗就隐藏
            this.subscribeFlag = true;
          } else {
            this.subscribeFlag = false;
          }
        }
        if (!this.isBgFlag) { 
          this.isBgFlag = !this.isBgFlag;
        }
        this.$nextTick(() => {
          document.getElementById("subscribe").scrollIntoView();
          this.makeOpen ? this.stopMove() : this.Move(); //判断滚动是否禁止滚动
        }, 1000);
      } else if (index === 1) {
        this.makeOpen = false;
        this.addressOpen = false;
        if (this.isBgFlag) {
          this.subscribeFlag = true;
        } else { 
          this.subscribeFlag = false;
        }
        this.query.is_recommand = 1;
        if(this.subscribeFlag || this.makeOpen || this.addressOpen) {
          this.backTop();
        }
      } else {
        this.fun
          .getLocation()
          .then(res => {
            let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
            this.query.latitude = p.lat;
            this.query.longitude = p.lng;
            let adcode = res.addressComponent.adcode;
            let interceptionCity = adcode.toString().slice(0, 4) + "00";
            if (this.addressCity === "") {
              this.addressCity = res.addressComponent.city;
              this.cityValue = interceptionCity;
            }
            this.query.cityCode = interceptionCity;
            this.locationStatus = true;
            this.aroundLocation();
            this.getGoodsList();
          })
          .catch(err => {
            console.log(err);
            this.locationStatus = false;
            this.getGoodsList();
          });
        this.makeOpen = false;
        this.addressOpen = false;
        if (this.isBgFlag) {
          this.subscribeFlag = true;
        } else { 
          this.subscribeFlag = false;
        }
        if(this.subscribeFlag) {
          this.backTop();
        }
      }
      if (!this.makeOpen) {
        this.Move();
      }
      

      this.subscribeIndex = index;
    },
    backTop () { //回到顶部
      const that = this
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5)
        document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
        if (that.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 16)
    },
    scrollToTop() {
      const that = this
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

      this.scrollTop = scrollTop;
    },
    maskOn() {
      //开启蒙版遮挡
      this.makeOpen = false;
      this.addressOpen = false;
      this.subscribeFlag = false;
      
      if (this.isBgFlag) {
        this.subscribeFlag = true;
      } else { 
        this.subscribeFlag = false;
      }
      // this.isBgFlag = false;
      this.Move();
    },
    //在这里插入代码片停止页面滚动
    stopMove() {
      document.body.style.overflow = "hidden";
    },
    //开启页面滚动
    Move() {
      document.body.style.overflow = "auto"; //出现滚动条
    },

    swiperNav(nav) {
      window.location.href = nav;
    },
    cityNavOn() {
      this.$router.push(this.fun.getUrl("tourCityList", {}, { cityCode: this.cityValue, city: this.addressCity, }));
    },
    commodityNav(id) {
      this.$router.push(this.fun.getUrl("tourAroundGoodsDetails", {}, { goodsId: id,latitude: this.query.latitude ,longitude:this.query.longitude}));
    },
    rankingNav() {
      this.$router.push(this.fun.getUrl("rankingList", {}, {localCity:this.localCity,cityCode: this.cityValue,latitude: this.query.latitude ,longitude:this.query.longitude}));
    },
    subscribeOption(index, name) {
      //选择评价的
      this.optionIndex = index;
      this.subscribeText = name;
      this.makeOpen = false;
      this.addressOpen = false;
      if(this.subscribeFlag || this.makeOpen || this.addressOpen) {
        this.backTop();
      }
      this.Move();
      this.query.travel_around_goods_type = index;
      this.query.page = 1;
      this.getGoodsList();
    },
    aroundLocation() {
      //获取站点信息
      $http.get("plugin.travel-around.frontend.index.index.getTravelAroundLocation", { cityCode: this.cityValue, city: this.addressCity }, "加载中..").then(response => {
        if (response.result == 1) {
          let res = response.data;
          this.addressList = res.matching || [];
        } else {
          this.$dialog.alert({
            message: response.msg
          });
        }
      });
    },
    toAddress(index, item) {
      this.addIndex = index;
      this.cityText = item;
      this.query.city = item;
      this.addressOpen = false;
      if(this.subscribeFlag || this.subscribeFlag || this.subscribeFlag) {
        this.backTop();
      }
      this.getGoodsList();
      this.Move();
      this.$nextTick(() => {
        document.getElementById("subscribe").scrollIntoView();
      }, 1000);
    },
    allArea() {
      this.addIndex = -1;
      this.cityText = "全部区域";
      this.addressOpen = false;
      this.isBgFlag =false;
      this.Move();
    },
    getGoodsList(isLocation) {
      if (this.query.latitude === "" && this.query.longitude === "") {
        this.locationMore = false;
      } else {
        this.locationMore = true;
      }
      this.goodsFlag = false;
      $http.post("plugin.travel-around.frontend.goods.goods.getGoodsList", this.query, "加载中..").then(response => {
        if (response.result == 1) {
          let res = response.data;
          this.isLoadMore = true;
          this.total_page = res.last_page;
          if (!this.total_page) {
            this.query.page = 0;
          }
          this.goodsList = res.data;
          if (response.basic_info && response.basic_info.home) {
            this.fun.setWXTitle(response.basic_info.home.mailInfo.name || "首页");
          }
          if(isLocation && !this.query.cityCode) {
            this.locationFun();
          }
          this.goodsFlag = true;
        } else {
          this.query.page = this.query.page - 1;
          this.isLoadMore = false;
          this.goodsFlag = false;
          this.$dialog.alert({
            message: response.msg
          });
        }
      });
    },
    locationFun() {
      //有定位信息，根据定位的信息加载商品列表
      this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.query.latitude = p.lat;
        this.query.longitude = p.lng;
        let adcode = res.addressComponent.adcode;
        let interceptionCity = adcode.toString().slice(0, 4) + "00";
        this.query.cityCode = interceptionCity;
        this.cityValue = interceptionCity;
        if(this.addressCity === '') {
          this.addressCity = res.addressComponent.city;
        }
        this.locationStatus = true;
        this.aroundLocation();
        this.getGoodsList();
        this.travelIndexData();
      })
      .catch(err => {
        this.locationStatus = false;
        this.aroundLocation();
        this.getGoodsList();
        this.travelIndexData();
      })
    },
    addMenuOpen() {
      this.addressOpen = true;
      this.makeOpen = false;
      this.subscribeIndex = 4;
      // this.subscribeFlag = !this.subscribeFlag;
      
      if (this.isBgFlag) { //吸顶不吸顶的判断是否显示背景色
        this.subscribeFlag = true;
      } else { 
        this.subscribeFlag = false;
      }
      if (this.addressOpen) { 
        this.subscribeFlag = true;
      }

      if (!this.isBgFlag) { 
        this.isBgFlag = !this.isBgFlag;
      }
      this.$nextTick(() => {
        document.getElementById("selectAddress").scrollIntoView();
        this.addressOpen ? this.stopMove() : this.Move();
      }, 1000);
    },
    classifyOn(index) {
      this.$router.push(this.fun.getUrl("tourAroundCategories", {}, {childrenId: index ,city: this.query.city , cityCode: this.query.cityCode,latitude: this.query.latitude ,longitude:this.query.longitude}));
    },
    headSitcky: debounceEnd(function (msg) { 
      let scrollTop = msg.scrollTop;
      if (scrollTop >= 15) {
        this.isBgFlag = true;
        // this.subscribeFlag = true;
      } else { 
        this.isBgFlag = false;
        this.subscribeFlag = false;
      }
    },50),
    points(backTime) {
      //判断是否到最后一天了
      let TimeDate = new Date(Number(backTime));
      let disposeTime = new Date(new Date(TimeDate).toLocaleDateString()).getTime();
      var date1 = new Date(new Date().toLocaleDateString()).getTime();
      return date1 === Number(disposeTime) ? true : false;
    },
    computingTime(afterTime, backTime) {
      //判断是否活动结束
      if (!Number(backTime)) return;
      let res = Number(afterTime) - Number(backTime);
      if (res === 0) {
        return true;
      }
      if (res > 0) {
        return true;
      } else {
        return false;
      }
    },
    timestampToTime(timestamp) {
      if (!timestamp) return;
      var date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "/";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "/";
      let D = this.change(date.getDate()) + " ";
      let h = this.change(date.getHours()) + ":";
      let m = this.change(date.getMinutes());

      // let s = this.change(date.getSeconds());
      return Y + M + D + h + m;
    },
    getGood() {
      $http
        .get("goods.customer-service.index", { goods_id: "",basic_info:1})
        .then(response => {
          if (response.result === 1) {
            let data = response.data;
            this.serviceQRcode = data.service_QRcode;
            this.serviceMobile = data.service_mobile;
            this.cservice = data.cservice;
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
    //获取更多数据
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.query.page >= this.total_page) {
        return;
      } else {
        this.query.page = this.query.page + 1;
        $http.post("plugin.travel-around.frontend.goods.goods.getGoodsList", this.query, "加载中").then(
          res => {
            this.isLoadMore = true;

            if (res.result === 1) {
              let myData = res.data.data;
              this.goodsList = [...this.goodsList, ...myData]; //数组拼接
            } else {
              this.query.page = this.query.page - 1;
              this.isLoadMore = false;
            }
          },
          function(response) {
            console.log("response", response);
            // error callback
          }
        );
      }
    },
    beforeDay(time) {
      //结束时间减去前一天
      return time - Number(this.presentTime);
    },
    beforeDayTime(time) {
      //获取结束时间的前一天
      let timeBefore = new Date(Number(time));
      timeBefore = +timeBefore - 1000 * 60 * 60 * 24;
      timeBefore = new Date(Number(timeBefore));
      return Number(timeBefore);
    }
  }
};
